package club.jdiy.dev.view;

import club.jdiy.core.JDiyContext;
import club.jdiy.core.ex.JDiyException;
import club.jdiy.utils.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

@Component
public class Handlers {
    @SuppressWarnings("ALL")
    public <T> Optional<T> getHandler(String clzzName, Class<T> t) {
        if (StringUtils.isEmpty(clzzName)) return Optional.empty();
        Class<?> clazz;
        T handler = null;
        try {
            clazz = Thread.currentThread().getContextClassLoader().loadClass(clzzName);
        } catch (Exception e) {
            throw new JDiyException("无法加载类：" + clzzName + "  错误信息：" + e.getMessage());
        }
        if (!t.isAssignableFrom(clazz)) throw new JDiyException("类" + clzzName + "不能转换为" + t.getSimpleName());
        try {
            handler = (T) jDiyContext.getApplicationContext().getBean(clazz);
        } catch (Exception ignore) {
            handler = null;
        }
        try {
            if (handler == null) handler = (T) clazz.newInstance();
        } catch (Exception e) {
            throw new JDiyException("类" + clzzName + "无法实例化,请检查默认构造函数. 错误信息：" + e.getMessage());
        }
        return Optional.ofNullable(handler);
    }

    @Resource
    JDiyContext jDiyContext;
}
